package com.jcfk.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.dao.RefRolePermissionMappingDao;
import com.jcfk.system.domain.dto.RefRolePermissionMappingDTO;
import com.jcfk.system.domain.po.RefRolePermissionMapping;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RefRolePermissionMappingService extends BaseService<RefRolePermissionMappingDao, RefRolePermissionMapping> {


    /**
     * 插入用户
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(RefRolePermissionMappingDTO dto) {

        // 查询现有所有权限
        QueryWrapper<RefRolePermissionMapping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", dto.getRoleId());
        RefRolePermissionMapping permissionMapping = new RefRolePermissionMapping();
        permissionMapping.setDeleted(1);
        permissionMapping.setLastUpdatedUserId(LoginUserInfoUtils.getUserId());
        permissionMapping.setLastUpdateTime(new Date());
        permissionMapping.setLastUpdatedUserName(LoginUserInfoUtils.getUserName());

        this.update(permissionMapping, queryWrapper);

        // 添加权限
        List<RefRolePermissionMapping> permissionMappings = new ArrayList<>();
        for (String permissionId : dto.getPermissionIds()) {
            RefRolePermissionMapping refRolePermissionMapping = new RefRolePermissionMapping();
            refRolePermissionMapping.setId(IdUtils.simpleUUID());
            refRolePermissionMapping.setRoleId(dto.getRoleId());
            refRolePermissionMapping.setRemarks(dto.getRemarks());
            refRolePermissionMapping.setPermissionId(permissionId);
            refRolePermissionMapping.setCreatedUserId(LoginUserInfoUtils.getUserId());
            refRolePermissionMapping.setCreateTime(new Date());
            refRolePermissionMapping.setCreatedUserName(LoginUserInfoUtils.getUserName());
            permissionMappings.add(refRolePermissionMapping);
        }

        // 保存
        if (permissionMappings.size() > 0) this.saveBatch(permissionMappings);
    }
}
